package com.hejjon.knowledgebase.interceptor;

import com.alibaba.fastjson.JSON;
import com.hejjon.knowledgebase.bean.ResponseResult;
import com.hejjon.knowledgebase.bean.ResultCodeEnum;
import com.hejjon.knowledgebase.constant.AuthConstant;
import com.hejjon.knowledgebase.constant.MessageConstant;
import com.hejjon.knowledgebase.model.dto.UserDTO;
import com.hejjon.knowledgebase.service.UserInfoService;
import com.hejjon.knowledgebase.util.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 *  登录拦截器
 * @author:
 * @date: 2022-12-06 13:46:51
 * @since: 1.0
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Resource
    private UserInfoService userInfoService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }
        String token = request.getHeader(AuthConstant.TOKEN_HEADER);
        if (StringUtils.isEmpty(token)) {
            log.error(">>>>>> token为空");
            writeResponse(response, ResultCodeEnum.HAVE_NO_PERMISSION.getRet(), MessageConstant.UNAUTHORIZED);
            return false;
        }
        // 解析token 获取用户信息
        UserDTO user = userInfoService.getUserByToken(token);
        if (user != null) {
            user.setIp(request.getRemoteAddr());
            UserHolder.set(user);
        } else {
            writeResponse(response, ResultCodeEnum.HAVE_NO_PERMISSION.getRet(), MessageConstant.USER_NOT_EXIST);
            return false;
        }
        return true;
    }


    private void writeResponse(HttpServletResponse response, int code, String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(JSON.toJSONString(ResponseResult.fail(code, msg)));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
